package com.ziyue.socket.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.ziyue.socket.bean.Member;
import com.ziyue.socket.bean.Room;
import com.ziyue.socket.bean.activity.Activity;
import com.ziyue.socket.bean.answer.AnswerRightResponse;
import com.ziyue.socket.bean.test.TestFinishRequest;
import com.ziyue.socket.enums.OptionEnum;
import com.ziyue.socket.enums.RoleEnum;
import com.ziyue.socket.service.OptionAbstract;
import io.netty.channel.Channel;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Created by wancheng on 2019/4/18.
 */
public class TestFinish extends OptionAbstract {

    private final OptionEnum OPTION = OptionEnum.TEST_FINISH;

    @Override
    public Object send(Channel channel, String requestBody) throws Exception {
        TestFinishRequest request = JSONObject.parseObject(requestBody, TestFinishRequest.class);
        Room room = roomManage.getRoom(channel);
        Activity activity = roomManage.getCurrentActivity(channel);
        activity.setEndTime(request.getEndTime());

        Map<String, Object> res = new HashMap<>(2);
        Map<String, Map<String, List<String>>> left = getLeft(room);
        List<AnswerRightResponse> right = getRight(room);
        res.put("left",left);
        res.put("right",right);
        //老师发送全部学生作答情况
        this.sendMsg(channel,"学生作答情况",res,OPTION);
        //学生发送各自的作答情况
        List<Member> students = room.getRoleMembers(RoleEnum.STUDENT);
        sendStudentAnswer(right,students);
        return null;
    }
    private void sendStudentAnswer(List<AnswerRightResponse> studentAnswer,List<Member> students){
        Map<String,AnswerRightResponse> accountMap = studentAnswer.stream().collect(Collectors.toMap(AnswerRightResponse::getAccount,p->p));
        for (Member student:students) {
            AnswerRightResponse answer = accountMap.get(student.getAccount());
            Channel studentChannel = channels.find(student.getChannelId());
            this.sendMsg(studentChannel,"老师收卷,返回学生的作答情况",answer,OPTION);
        }
    }

    @Override
    public Object get(Channel channel, String requestBody) {
        return null;
    }
}
